<template>
  <Panel class="car-detail-wrapper" :mainStyle="{ 'justify-content': 'flex-start' }" title="车辆详情" v-bind="$attrs">
    <!-- 切换切换栏 -->
    <div class="tabs-boxs">
      <div
        :class="state.activeTab === tab ? 'active-tab tab' : 'tab'"
        @click="switchTab(tab)"
        v-for="tab in tabs"
        :key="tab"
      >
        {{ tab }}
      </div>
    </div>

    <div :class="visible ? 'content-wrapper disabled-scroll' : 'content-wrapper'">
      <!-- 行驶轨迹 -->
      <div v-if="state.activeTab === '行驶轨迹'" class="scroll-list-wrapper scroll-hover">
        <div class="scroll-list">
          <div class="block" v-for="i in vehicleRoute" :key="i.id" @click="showTrajectory(i)">
            <template v-if="Array.isArray(i) && i.length">
              <div class="arrow-box">
                <svg-icon icon-class="right-arrow" className="right-arrow"> </svg-icon>
              </div>

              <template v-for="(item, index) in i" :key="item.id">
                <div class="block-row-1" v-if="index == 0">
                  <svg-icon icon-class="start" className="start"></svg-icon>
                  <span class="date">{{ proxy.$dayjs(item.transitTime).format('HH:mm:ss') }}</span>
                  <span class="position"
                    >经<span class="position-text">{{ item.entryName }}</span
                    >驶入</span
                  >
                </div>
                <div class="block-row" v-else-if="index == i.length - 1">
                  <svg-icon icon-class="end" className="start"></svg-icon>
                  <span class="date">{{ proxy.$dayjs(item.transitTime).format('HH:mm:ss') }}</span>
                  <span class="position"
                    >经<span class="position-text">{{ item.passingPointName }}</span
                    >驶出</span
                  >
                </div>
              </template>
            </template>
            <!-- <TransitionGroup name="list" tag="ul"> -->
            <!-- <div
                class="block-row"
                :class="{ 'block-row-1': index != testArr.length - 1 }"
                v-for="(item, index) in testArr"
                :key="item"
              >
                <svg-icon :icon-class="index != testArr.length - 1 ? 'start' : 'end'" className="start"></svg-icon>
                <span class="date"> 17:34:32 </span>
                <span class="position">经<span class="position-text">溧马苏皖省界入口匝道</span>驶入</span>
              </div> -->
            <!-- </TransitionGroup> -->
          </div>
          <Empty v-if="!vehicleRoute || !vehicleRoute.length" />
        </div>
        <a-drawer
          :closable="false"
          :mask="false"
          :style="drawerStyle"
          :get-container="false"
          v-if="visible"
          placement="top"
          :visible="visible"
        >
          <template #extra>
            <svg-icon icon-class="close" class="close" @click="onClose"></svg-icon>
          </template>
          <template #title>
            <div class="car-unit">{{ computedCarNum }}</div>
            <div class="car-time">{{ computedDate }}</div>
          </template>

          <a-timeline>
            <template v-for="(item, index) in state.violationRocordDetail" :key="item.id">
              <a-timeline-item>
                <template #dot v-if="index === 0">
                  <img src="../../assets/images/intelligent/start-point.png" alt="" class="start-point" />
                </template>
                <template #dot v-else-if="index === state.violationRocordDetail.length - 1">
                  <img src="../../assets/images/intelligent/end-point.png" alt="" class="start-point" />
                </template>
                <template #dot v-else> {{ index }} </template>
                <div class="content">
                  <span>{{ item.passingPointName }}</span>
                  <span>{{ proxy.$dayjs(item.transitTime).format('HH:mm:ss') }}</span>
                </div>
              </a-timeline-item>
            </template>
          </a-timeline>
        </a-drawer>
      </div>

      <div class="car-info-wrapper" v-if="state.activeTab === '车辆信息'">
        <div class="row" v-for="item in carInfoList" :key="item.id">
          <span>{{ item.label }}</span>
          <span>{{ item.render ? item.render(carInfoObj, item.key) : carInfoObj[item.key] }}</span>
        </div>
      </div>

      <div class="permit-info-wrapper" v-if="state.activeTab === '许可证件'">
        <div class="row" v-for="item in permitInfoList" :key="item.id">
          <span>{{ item.label }}</span>
          <span>{{ item.render ? item.render(permitObj, item.key) : permitObj[item.key] }}</span>

          <template v-if="item.label == '营运路线'">
            <!-- <div class="operat-line" v-for="(value, index) in 2" :key="value.id">
              <span class="city-name"> 江苏省 </span>
              <span class="content"
                >南京市栖霞区新港开发区10号南京市栖霞区新港开发区10号--G42沪蓉高速--G1522常台高速--苏沪界</span
              >
            </div> -->
          </template>
        </div>
        <Empty v-if="!permitInfoList || !permitInfoList.length" />
      </div>

      <div class="violation-records" v-if="state.activeTab === '违规信息'">
        <!-- //:ghost="true" -->
        <div class="violation-header">
          <span class="type">违规类型</span>
          <span class="date">日期</span>
          <span class="status">处理结果</span>
        </div>

        <div class="collapse-container scroll-hover">
          <a-collapse expand-icon-position="right" @change="collapseChange" :ghost="false" :accordion="true">
            <a-collapse-panel :showArrow="false" v-for="item in state.violationRocords" :key="item.key" class="active">
              <template #extra>
                <span class="type">{{ item.violationType }}</span>
                <span class="date">{{ dateFormat(item.violationTime) }}</span>
                <span class="status">{{ item.resultCode }}</span>
              </template>
              <div class="collapse-content">
                <a-spin class="spin" v-if="violationProcess && !violationProcess.length" />
                <a-steps progress-dot direction="vertical" v-model:current="current">
                  <template>
                    <!-- <template #progressDot="{ index, status, prefixCls }"> -->
                    <a-popover>
                      <template #icon>
                        <svg-icon icon-class="start" className="start"></svg-icon>
                      </template>
                    </a-popover>
                  </template>
                  <a-step v-for="item in violationProcess" :key="item.time">
                    <template #title>
                      <span class="status">{{ item.linkName }}</span>
                      <span class="step">{{ item.time }} </span>
                    </template>
                  </a-step>
                </a-steps>
              </div>
            </a-collapse-panel>
          </a-collapse>
          <Empty v-if="!state.violationRocords || !state.violationRocords.length" />
        </div>
      </div>

      <a-spin class="spin-loading" v-show="spinning" />
    </div>
  </Panel>
</template>
<script>
export default {
  name: 'CarDetail'
}
/**
 * @desc  重点车辆详情
 * @auther 邓清波
 * @date  2022/10/26
 * **/
</script>

<script setup>
import Panel from '../../components/panel'
import { ref, reactive, getCurrentInstance, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import useMapOperates from '@/hooks/useMapOperates'
import Empty from '../../components/empty'
import monitorApi from '../../api/monitor'
import { parseTime } from '@/utils'
import baseServiceApi from '../../api/base-service'

const tabs = ref(['行驶轨迹', '车辆信息', '许可证件', '违规信息'])
const current = ref(10)
const state = reactive({
  activeTab: '行驶轨迹',
  violationRocords: [], // 形式轨迹列表
  violationRocordDetail: [], // 形式轨迹详细 ，
  row: {}
})

// 形式轨迹详情车牌
const computedCarNum = computed(() => (state.violationRocordDetail[0] ? state.violationRocordDetail[0].carPlate : ''))

// 形式轨迹详情时间
const computedDate = computed(
  () =>
    state.violationRocordDetail[0] &&
    state.violationRocordDetail[0].transitTime &&
    proxy.$dayjs(state.violationRocordDetail[0].transitTime).format('YYYY-MM-DD')
)

let drivingInstance = null

const store = useStore()
// 点位、弹框的处理
const handleDark = useMapOperates()
const mapperResultCode = {
  0: '未处理',
  1: '已处理' // 处理中
}
// loading
const spinning = ref(false)
// 车辆信息
const carInfoList = [
  {
    label: '车牌号',
    key: 'plateNum'
  },
  {
    label: '车型',
    key: 'carType'
  },
  {
    label: '车牌颜色',
    key: 'plateColor'
  },
  {
    label: '车辆长宽高 （m）',
    key: ['length', 'width', 'height'],
    render: concatLWH
  },
  {
    label: '荷载重量 （吨）',
    key: 'loadWeight'
  },
  {
    label: '轮胎数',
    key: 'tyreCount'
  },
  {
    label: '轴距',
    key: 'wheelbase'
  }
]
const carInfoObj = ref({})

// 许可证件信息字段
const permitInfoList = [
  {
    label: '承运单位',
    key: 'carrierCompany'
  },
  {
    label: '经营许可证号',
    key: 'licenceNo'
  },
  {
    label: '许可证有效期',
    key: ['licenceValidityStartTime', 'licenceValidityEndTime'],
    render(record, key) {
      return `${record[key[0]] || ''}-${record[key[1]] || ''}`
    }
  },
  {
    label: '货物信息',
    key: 'goodsInfo'
  },
  {
    label: '货物重量 （吨）',
    key: 'goodsWeight'
  },
  {
    label: '货物长宽高 （米）',
    key: ['goodsLength', 'goodsWidth', 'goodsHeight'],
    render: concatLWH
  },

  {
    label: '营运路线',
    key: '?'
  }
]
const permitObj = ref({})

const drawerStyle = {
  height: '100%',
  'overflow-y': 'auto',
  position: 'absolute'
}
const { proxy } = getCurrentInstance()

const visible = ref(false)

const violationProcess = ref([]) // 违规记录过程

// 车辆轨迹列表
const vehicleRoute = ref([])
const testArr = ref([{}, {}])
onMounted(() => {
  proxy.$bus.on('vehicleClick', function (params) {
    state.row = params
    getData()
  })
})

/**
 * 监听列表重点车辆点击 - 获取数据
 * **/
const getData = async () => {
  spinning.value = true
  const params = { id: state.row ? state.row.id : '' }
  onClose()
  try {
    if (state.activeTab == '行驶轨迹') {
      // 车辆轨迹
      await monitorApi.getVehicleRoute(params).then(res => {
        vehicleRoute.value = res.data
      })
    } else if (state.activeTab == '车辆信息') {
      // 车辆信息
      await monitorApi.getVehicleInfo(params).then(res => {
        carInfoObj.value = res.data
      })
    } else if (state.activeTab == '许可证件') {
      // 许可证件
      await monitorApi.getVehicleLicence(params).then(res => {
        permitObj.value = res.data
      })
    } else if (state.activeTab == '违规信息') {
      // 违规信息列表
      await monitorApi.getVehicleViolation(params).then(res => {
        state.violationRocords = res.data
      })
    }
    spinning.value = false
  } catch (e) {
    spinning.value = false
  }
}

/**
 * @desc 格式时间
 *
 * **/
function dateFormat(date) {
  if (!date) return ''
  return proxy.$dayjs(date).format('YYYY-MM-DD')
}

function switchTab(tab) {
  state.activeTab = tab
  getData()
  visible.value = false
}

/**
 * @param 行驶轨迹箭头点击
 */
function showTrajectory(item) {
  store.commit('config/SET_DETAIL_CONFIG', {
    data: item
  })
  setTimeout(() => {
    drawLayer(item)
  })
  state.violationRocordDetail = item || []
  // testArr.value.splice(1, 0, {}, {})
  showDrawer()
}

const showDrawer = () => {
  visible.value = true
}

const onClose = () => {
  visible.value = false
  console.log('drivingInstance', drivingInstance)
  drivingInstance && drivingInstance.clear()

  store.commit('config/SET_DETAIL_CONFIG', {
    data: {}
  })
}

/**
 * 展开违规记录事件
 * @param key 行key
 * **/
function collapseChange(key) {
  if (!key) return
  // 违规记录过程 violationProcess
  monitorApi.getVehicleViolationProcess(key).then(res => {
    violationProcess.value = res.data || []
  })
}

/**
 * 拼接长宽高
 * **/
function concatLWH(redord = {}, keys) {
  try {
    const lengthValue = redord[keys[0]] ? redord[keys[0]] + '*' : ''
    const WidthValue = redord[keys[1]] ? redord[keys[1]] + '*' : ''
    const heightValue = redord[keys[2]] ? redord[keys[2]] : ''

    return `${lengthValue}${WidthValue}${heightValue}`
  } catch (e) {
    console.log('error:' + e)
  }
}

/**
 * 地图图层操作
 */
const drawLayer = data => {
  const polylineWaypoints = data.map(i => i)
  const path = data.map(item => [item.lon, item.lat])

  // polylineWaypoints.slice(1, polylineWaypoints.length - 1)

  // const starRoadNum = data[0].roadNum;
  // const startZh = data[0].zh;
  // const endRoadNum = data[data.length - 1].roadNum
  // const endZh = data[data.length - 1].zh

  // let path = []
  // vehicleRoute.value.map(i => {
  //   i.map(item => path.push([item.lon, item.lat]))
  // })
  console.log('drivingInstance', drivingInstance)

  drivingInstance && drivingInstance.clear()
  const startLngLat = path[0] // 开始位置
  const endLngLat = path[[path.length - 1]] // 终点位置
  let waypoints = [] // 途径点

  if (path.length > 2) {
    waypoints = path.slice(1, path.length - 1)
  }
  console.log('startLngLat', startLngLat)
  console.log('endLngLat', endLngLat)
  console.log('waypoints', waypoints)
  drivingInstance = new AMap.Driving({
    policy: AMap.DrivingPolicy.LEAST_TIME,
    map: window._map
  })

  drivingInstance.search(startLngLat, endLngLat, { waypoints: waypoints }, function (status, result) {
    console.log('result', result)
    if (status !== 'complete') {
      proxy.$message.warning('经纬度缺失，绘制路线失败')
    }
    polylineWaypoints.map(i => {
      handleDark(
        'marker',
        [
          {
            ...i,
            icon: 'gs-mj',
            path: [i.lon, i.lat],
            name: i.passingPointName,
            size: [30, 35],
            offset: [-14, -35],
            zIndex: 101
          }
        ],
        { type: 'gs-mj' }
      )
    })
  })

  // baseServiceApi.getBaseInfoList({
  //   roadNum:starRoadNum,
  //   startStake
  // })
  // handleDark(
  //   'marker',
  //   [
  //     {
  //       icon: 'zhdd-gl-sxj',
  //       path: path[0],
  //       name: '摄像头',
  //       size: [30, 35]
  //     }
  //   ],
  //   { type: 'sxj' }
  // )
}
</script>
<style scoped lang="less">
@import url(../../styles/themes/index.less);
@import url(~@/assets/styles/transition.less);
@primary: #3385ff;

.car-detail-wrapper {
  .tabs-boxs {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 7px;

    .tab {
      text-align: center;
      font-weight: 700;
      flex: 1;
      margin: 0 3px;
      font-size: 14px;
      line-height: 14px;
      height: 14px;
      color: #333;
      border-right: 1px solid #c4c4c4;
      cursor: pointer;
    }

    .active-tab {
      color: @primary;
    }

    .tab:last-child {
      border-right: none;
    }
  }

  .content-wrapper {
    flex: 1;
    overflow-y: auto;
    margin-top: 12px;
    position: relative;
  }

  .disabled-scroll {
    flex: 1;
    overflow-y: hidden;
    position: relative;
  }

  .scroll-list-wrapper {
    height: 100%;
    overflow: inherit;
    position: relative;

    .scroll-list {
      height: 100%;
      display: flex;
      flex-direction: column;

      .block {
        // min-height: 76px;
        margin: 0 13px 10px 13px;
        padding: 3px 12px 7px 17px;
        background-color: #fff;
        cursor: pointer;

        ul {
          padding: 0;
          margin-bottom: 5px;
          max-height: 270px;
          overflow-y: auto;
          overflow-x: hidden;
        }

        .block-row {
          display: flex;
          align-items: center;
          line-height: 25px;
          width: 95%;

          .start {
            width: 13px;
            height: 13px;
            z-index: 2;
          }

          .end {
            width: 13px;
            height: 13px;
            z-index: 2;
            margin-top: 10px;
          }

          .date {
            // width: 60px;
            font-size: 14px;
            text-align: left;
            color: #333333;
            // margin-left: 4px;
          }
        }

        .arrow-box {
          padding-top: 10px;

          .right-arrow {
            float: right;
            width: 16px;
            height: 10px;
            cursor: pointer;
          }
        }

        .position-text {
          color: #009dff;
        }

        .position {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .block-row-1 {
        position: relative;
        width: 95%;

        &::before {
          position: absolute;
          content: '';
          height: 16px;
          width: 2px;
          background-color: @primary;
          top: 66%;
          left: 5px;
        }
      }

      .block:last-child {
        margin-bottom: 0;
      }
    }
  }

  .car-info-wrapper,
  .permit-info-wrapper {
    flex: 1;
    padding: 0 18px;
  }

  .violation-records {
    flex: 1;
    padding: 0 3px;

    .violation-header {
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      text-align: left;
      background: #dee5f2;
      padding: 10px 0;
    }

    .collapse-container {
      height: calc(100% - 32px);
    }
  }

  .row {
    min-height: 33px;
    align-items: center;
    line-height: 33px;
    color: #333;
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #d5e0f2;
    flex-wrap: wrap;

    .operat-line {
      width: 100%;
      display: flex;

      .city-name {
        width: 35%;
      }

      .content {
        word-wrap: break-word;
        word-break: break-all;
        color: #666;
      }
    }
  }
}

/deep/.ant-drawer-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  text-align: center;
}

/deep/.ant-timeline-item-head-custom {
  width: 16px;
  height: 16px;
  background: #ffbe00;
  border-radius: 50% 50%;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #333333;

  .start-point {
    width: 100%;
    height: 100%;
  }
}

.car-unit {
  width: 78px;
  height: 22px;
  background: #ffbe00;
  border-radius: 2px;
  color: #333;
  font-size: 14px;
}

.car-time {
  margin-right: 10px;
}

.close {
  cursor: pointer;
  margin-bottom: 2px;
}

.type {
  padding-left: 15px;
}

.status {
  // width: 20%;
  padding-right: 15px;
}

/deep/ .ant-drawer-header {
  border-bottom: none;
  padding: 10px 20px;
}

/deep/ .ant-drawer-header,
/deep/.ant-drawer-body {
  background-color: #e8effc;
  padding-bottom: 0;
}

/deep/.ant-timeline-item-tail {
  border-left: 2px solid #c2dcfe;
}

/deep/ .ant-drawer-content-wrapper {
  height: 100% !important;
  box-shadow: none;
}

/deep/ .ant-collapse-header {
  padding: 0.1rem 0 !important;
}

/deep/ .ant-collapse-extra {
  display: flex;
  justify-content: space-between;
  margin: 0;
  width: 100%;

  .type {
    padding-left: 15px;
    flex: 4;
  }

  .status {
    // width: 20%;
    padding-right: 15px;
    text-align: center;
    flex: 2;
  }

  .date {
    flex: 3;
  }
}

/deep/ .ant-collapse-item,
.ant-collapse {
  border: 0;
  background-color: transparent;
}

.ant-collapse-item.ant-collapse-item-active /deep/.ant-collapse-header {
  background: #e7f1ff;
  border: 1px solid #3385ff8a;
  box-shadow: inset 0 0 10px #3385ff42;
}

/deep/ .ant-collapse-item {
  background: #e9f2fe;
}

/deep/ .ant-collapse-header:hover {
  background: #b0caff;
}

.collapse-content {
  position: relative;
  height: auto;
  background-color: #fff !important;
  border-radius: 10px;
  padding-left: 15px;

  .spin {
    width: 100%;
    height: 100px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  &::before {
    content: '';
    position: absolute;
    top: -10px;
    right: 4%;
    width: 0;
    height: 0;
    border-left: 20px solid transparent;
    border-right: 20px solid transparent;
    border-bottom: 20px solid #fff;
  }

  .collapse-content-row {
    font-size: 14px;
    display: flex;

    .start {
      padding-left: 14px;
      width: 10px;
      height: 10px;
      color: #009dff;
    }

    .step {
      padding-left: 10px;
      color: #009dff;
    }

    .date {
      padding-left: 5px;
    }
  }
}

/deep/ .ant-collapse-content-box {
  background-color: #e6f0fc;
}

/deep/ .ant-steps-icon .start {
  font-size: 10px;
}

.content {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

/deep/ .ant-collapse-content-box {
  padding: 12px 0 0 0;

  .ant-steps-item-title {
    display: flex;

    .status {
      width: 20%;
      font-size: 14px;
      color: #3385ff;
    }
  }
}
</style>
